# -*- coding: utf-8 -*-
# @Time    : 2021/6/28 10:26
# @Author  : zcn
# @Software: PyCharm

import os

from fastapi import APIRouter
from re_common.baselibrary.utils.basedir import BaseDir
from re_common.baselibrary.utils.basefile import BaseFile

from apps.allsubdb.git_pull_ctrl.models import GitAndUpdate
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo, SUCCESS
from apps.core.global_model import InputPlatformModel

router = APIRouter(route_class=ContextIncludedRoute)

# 函数区
#-----------------------------------------------------------------------
def kill_port(port):
    with os.popen(f'netstat -aon|findstr "{port}"') as res:
        res = res.read().split('\n')
    result = []
    for line in res:
        temp = [i for i in line.split(' ') if i != '']
        if len(temp) > 4:
            result.append({'pid': temp[4], 'address': temp[1], 'state': temp[3]})
    for one_data in result:
        state = one_data["state"]
        if state == "LISTENING":
            pid = one_data["pid"]
            result1 = os.popen(f"taskkill -pid {pid} -f")
            break

# API区
#------------------------------------------------------------------------

@router.get("/git_ctrl/pull")
async def get_server_except():
    '''
    针对服务器进行git_pull
    :return:
    '''
    return_info = ReturnInfo()
    cur_path = BaseDir.get_file_dir_absolute(__file__)
    top_path = BaseDir.get_upper_dir(cur_path, -3)
    adb = f"cd {top_path} & git pull"
    data = os.system(adb)
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "更新完成"
    return_info.data = data
    return return_info.todict()


@router.post("/git_ctrl/update")
async def get_server_except(input: InputPlatformModel[GitAndUpdate]):
    '''
    增加参数, 以达到在各个服务器上面进行安装包或者更新包的操作
    :return:
    '''
    return_info = ReturnInfo()
    sentence = input.data.sentence
    cur_path = BaseDir.get_file_dir_absolute(__file__)
    top_path = BaseDir.get_upper_dir(cur_path, -3)
    adb = f"cd {top_path} & {sentence}"
    data = os.system(adb)
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "更新完成"
    return_info.data = data
    return return_info.todict()

@router.post("/git_ctrl/port_reboot")
async def get_server_except(input: InputPlatformModel[GitAndUpdate]):
    '''
    处理重启端口问题
    zcn: 此端口输入一个端口号  8001   即可自动启动, 问题在于不是以cmder启动,
    :return:
    '''
    return_info = ReturnInfo()
    port = input.data.sentence
    bat_name = f"{port}.bat"

    cur_path = BaseDir.get_file_dir_absolute(__file__)
    top_path = BaseDir.get_upper_dir(cur_path, -3)
    bat_locl_name = BaseFile.get_new_path(top_path, bat_name)
    kill_port(port)
    bat_data = f"@echo off\nstart python main.py --port {port} --tags local_test"
    for path, dirNames, fileNames in os.walk(top_path):
        if bat_name not in fileNames:
            with open(bat_locl_name, mode="w", encoding="utf-8") as f:
                f.write(bat_data)
    os.system(bat_name)
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "更新完成"
    return_info.data = ""
    return return_info.todict()


